﻿Imports ISNet.WebUI.WebGrid
Imports System.Data
Imports log4net

Partial Class CopyVersionAdvance
    Inherits System.Web.UI.Page

    Public AlertText As String
    Public ScriptText As String

    Private Shared logger As ILog = LogManager.GetLogger("CopyVersionAdvance")

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        Session.LCID = 2057
        If Session("users") Is Nothing Then
            Response.Redirect("LoginForm.aspx")
        End If

        If IsPostBack = False Then
            PlanYearsTxt.Text = Val(Session("PlanYear"))
            planyearS.Text = Val(Session("PlanYear"))
            planyearD.Text = Val(Session("PlanYear"))
            planyearT.Text = Val(Session("PlanYear"))

            If Session("UserCombo") IsNot Nothing Then
                UsersWebCombo.Value = Session("UserCombo")
                Session.Remove("UserCombo")
                AlertText = "<script>window.scrollTo(0,document.body.scrollHeight);</script>"
            End If

        End If

        'Alert(UsersWebCombo.Value)

        'If IsPostBack = False Then
        ' Alert(UsersWebCombo.Value)
        Session("usersNow") = UsersWebCombo.Value '"bb9222" 


        If UsersWebCombo.Value <> "" Then
            'WebGrid1.ClearCachedDataSource()
            'WebGrid1.ClientAction.Refresh()
            Dim Myversion As Integer
            Dim username As String = Session("usersNow")

            Dim top_fct As String
            Dim version As Integer
            GetTopFct(username, PlanYearsTxt.Text, 1, top_fct, version)


            ' Response.Write("top" & top_fct)
            ' Exit Sub

            Dim FCTDataSet As New DataSet
            Try
                GetChildWithVersion(top_fct, PlanYearsTxt.Text, 1, FCTDataSet, Myversion)

            Catch ex As Exception
                Alert("ไม่มีหน่วยงานลูก")
                Exit Sub
            End Try

            Dim adap As New FundCenter2TableAdapters.fundCenterDetailTableAdapter
            Dim nowVersion As Integer = 0
            Try
                nowVersion = adap.getNowVersion(top_fct, PlanYearsTxt.Text)
            Catch ex As Exception
                nowVersion = 1
            End Try

            If FCTDataSet.Tables(0).Rows.Count < 2 Then
                ' Response.Redirect("Default.aspx")
                Alert("ไม่มีหน่วยงานลูก")
            End If

            If nowVersion > Myversion Then
                coppy_btn.Visible = False
                ForceCopyBtn.Visible = False
            Else
                coppy_btn.Visible = True
                ForceCopyBtn.Visible = True
            End If
            'Response.Write(nowVersion & "  " & Myversion)
            HdUser.Value = Session("usersNow")
            HdMyVersion.Value = Myversion
            WebGrid1.DataSource = FCTDataSet.Tables("Items")

            Dim adapr As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
            'countr = adapr.checkCopy(Session("TopFctr"), version, Val(Session("PlanYear")))

            Dim lastflag As String = ""
            Try
                lastflag = adapr.GetLastFlag(Session("TopFctr"), version, Val(Session("PlanYear")))
            Catch ex As Exception
                lastflag = ""
                logger.Error(ex.Message)
                logger.Error(ex.StackTrace)
            End Try

            Dim reflag As String = ""
            Try
                reflag = adapr.GetReleaseFlag(Session("TopFctr"), version, Val(Session("PlanYear")))
            Catch ex As Exception
                reflag = ""
                logger.Error(ex.Message)
                logger.Error(ex.StackTrace)
            End Try


            If nowVersion = version Then
                If reflag = "N" And lastflag = "Y" Then
                    ImageButton1.Visible = True
                Else
                    ImageButton1.Visible = False
                End If
            Else
                ImageButton1.Visible = False
            End If
            If nowVersion = 1 Then
                ImageButton1.Visible = False
            End If
        End If
        ' End If

        If Session("pageindex") IsNot Nothing Then
            WebGrid1.SetCurrentPageIndex(Val(Session("pageindex")))
            Session.Remove("pageindex")
        End If
    End Sub


    Sub GetChildWithVersion(FundCenterCode As String, PlanYear As Decimal, FctGroup As String, ByRef ds As DataSet, ByRef CopyToVersion As Integer)


        Dim dt As DataTable = ds.Tables.Add("Items")
        dt.Columns.Add("FundCenterCode", Type.GetType("System.String"))
        dt.Columns.Add("FundCenterName", Type.GetType("System.String"))
        dt.Columns.Add("now_version", Type.GetType("System.Int32"))
        dt.Columns.Add("level", Type.GetType("System.Int32"))

        dt.Columns.Add("CreateDate", Type.GetType("System.String"))
        dt.Columns.Add("ReleaseFlag", Type.GetType("System.String"))
        Dim Radapter As New FundCenterRelationTableAdapters.FundCenterReleasesTableAdapter
        Dim Rdatatable As New FundCenterRelation.FundCenterReleasesDataTable
        Dim Fadapter As New FundCenterRelationTableAdapters.FundCenterHierarchiesTableAdapter
        Dim Fdatatable As New FundCenterRelationTableAdapters.FundCenterHierarchiesTableAdapter
        Dim Hadapter As New FundCenterRelationTableAdapters.FctHTableAdapter
        Dim Hdatatable As New FundCenterRelation.FctHDataTable
        Dim Cdatatable As New FundCenterRelation.FctHDataTable
        Dim Badapter As New FundCenterRelationTableAdapters.BudgetDetailsTableAdapter

        Hdatatable = Hadapter.GetDataByFctCode(FundCenterCode, PlanYear, FctGroup)
        Dim RootGroupPath As String = ""

        If Hdatatable.Count = 0 Then
            Exit Sub
        End If
        Dim r As DataRow
        'add root
        For Each Hrow As FundCenterRelation.FctHRow In Hdatatable
            RootGroupPath = Hrow.grouppath
            r = dt.NewRow()
            r("FundCenterCode") = Hrow.FundCenter_FundCenterCode
            r("FundCenterName") = Hrow.Description
            r("level") = Val(Left(Fadapter.GetOrgLevel(Hrow.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))
            CopyToVersion = r("level")
            r("now_version") = 1
            Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

            r("CreateDate") = ""
            r("ReleaseFlag") = ""
            For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable
                r("CreateDate") = If(rrow.IsUpdatedDateNull, rrow.CreatedDate, rrow.UpdatedDate)
                r("ReleaseFlag") = rrow.ReleaseFlag
            Next
            If r("ReleaseFlag") = "" Then
                If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
                    r("ReleaseFlag") = "N"
                End If
            End If
            dt.Rows.Add(r)
        Next
        'get child 1 level
        Hdatatable = Hadapter.GetDataByGroupPath(RootGroupPath & "__", PlanYear, FctGroup)
        Dim version As Integer
        For Each row As FundCenterRelation.FctHRow In Hdatatable
            r = dt.NewRow()
            r("FundCenterCode") = row.FundCenter_FundCenterCode
            r("FundCenterName") = row.Description
            r("level") = Val(Left(Fadapter.GetOrgLevel(row.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))
            'get child all
            Cdatatable = Hadapter.GetDataByGroupPath(row.grouppath & "%", PlanYear, FctGroup)
            If Cdatatable.Count = 0 Then
                r("now_version") = 1
            Else
                r("now_version") = r("level")
            End If
            version = r("now_version")
            Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

            r("CreateDate") = ""
            r("ReleaseFlag") = ""
            For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable
                r("CreateDate") = If(rrow.IsUpdatedDateNull, rrow.CreatedDate, rrow.UpdatedDate)
                r("ReleaseFlag") = rrow.ReleaseFlag
            Next
            If r("ReleaseFlag") = "" Then
                If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
                    r("ReleaseFlag") = "N"
                End If
            End If

            dt.Rows.Add(r)
            'insert child
            For Each crow As FundCenterRelation.FctHRow In Cdatatable
                r = dt.NewRow()
                r("FundCenterCode") = crow.FundCenter_FundCenterCode
                r("FundCenterName") = crow.Description

                r("level") = Val(Left(Fadapter.GetOrgLevel(crow.FundCenter_FundCenterCode, PlanYear, FctGroup), 1))

                r("now_version") = version

                Rdatatable = Radapter.GetDataByFCT(r("FundCenterCode"), PlanYear, r("now_version"))

                r("CreateDate") = ""
                r("ReleaseFlag") = ""
                For Each rrow As FundCenterRelation.FundCenterReleasesRow In Rdatatable
                    r("CreateDate") = If(rrow.IsUpdatedDateNull, rrow.CreatedDate, rrow.UpdatedDate)
                    r("ReleaseFlag") = rrow.ReleaseFlag
                Next
                If r("ReleaseFlag") = "" Then
                    If Badapter.CountRecord(r("FundCenterCode"), PlanYear, r("now_version")) > 0 Then
                        r("ReleaseFlag") = "N"
                    End If
                End If
                dt.Rows.Add(r)
            Next



        Next

    End Sub


    Sub GetTopFct(username As String, PlanYear As Decimal, FctGroup As String, ByRef fctCode As String, ByRef version As Integer)
        Dim adapter As New FundCenter2TableAdapters.FundCenterHierarchiesTableAdapter
        Dim datatable As New FundCenter2.FundCenterHierarchiesDataTable
        datatable = adapter.GetTopFctByUser(username, PlanYear, FctGroup)
        'Response.Write(username & "/" & PlanYear & "/" & FctGroup)
        Try
            For Each row As FundCenter2.FundCenterHierarchiesRow In datatable
                fctCode = row.FundCenter_FundCenterCode
                Dim level As Integer = Val(Left(row.OrgLevel, 1))
                version = level
            Next

        Catch ex As Exception
            fctCode = ""
            version = 1
        End Try


    End Sub

    Protected Sub WebGrid1_InitializeDataSource(sender As Object, e As DataSourceEventArgs) Handles WebGrid1.InitializeDataSource
        If WebGrid1.RootTable.Rows.Count = 0 Then
            Dim FCTDataSet As New DataSet
            Dim dt As DataTable = FCTDataSet.Tables.Add("Items")
            dt.Columns.Add("FundCenterCode", Type.GetType("System.String"))
            dt.Columns.Add("FundCenterName", Type.GetType("System.String"))
            dt.Columns.Add("now_version", Type.GetType("System.Int32"))
            dt.Columns.Add("level", Type.GetType("System.Int32"))

            dt.Columns.Add("CreateDate", Type.GetType("System.String"))
            dt.Columns.Add("ReleaseFlag", Type.GetType("System.String"))
            e.DataSource = dt
        End If
        'Dim Myversion As Integer
        'Dim username As String = Session("users")

        'Dim top_fct As String
        'top_fct = GetTopFct(username, PlanYearsTxt.Text, 1)
        'Dim FCTDataSet As New DataSet
        'GetChildWithVersion(top_fct, PlanYearsTxt.Text, 1, FCTDataSet, Myversion)
        'HdMyVersion.Value = Myversion
        'WebGrid1.DataSource = FCTDataSet.Tables(0)
    End Sub

    Protected Sub WebGrid1_InitializePostBack(sender As Object, e As PostbackEventArgs) Handles WebGrid1.InitializePostBack

        If e.Action = PostBackAction.Custom Then
            Dim ActionType As String = TryCast(Request("type"), String)
            If ActionType = "1" Then
                'WebGrid1.ClientAction.Alert("post1")
                'WebGrid1.ClientAction.Refresh()
                'Exit Sub

                Dim dd As New DataTable
                dd = WebGrid1.DataSource
                Dim count As Integer = 0
                For Each row As DataRow In dd.Rows
                    ' WebGrid1.ClientAction.Alert(row.Item("FundCenterCode"))
                    Try
                        If row.Item("ReleaseFlag") = "N" And Val(row.Item("level")) < 4 Then
                            count = count + 1
                        End If
                        If row.Item("ReleaseFlag") = "" Then
                            count = count + 1
                        End If
                    Catch ex As Exception
                        count = count + 1
                    End Try

                Next
                If count > 0 Then
                    WebGrid1.ClientAction.Alert("มีหน่วยงาน ยังไม่ได้ส่งแผน ไม่สามารถ Copy Version ได้ในขณะนี้")
                    WebGrid1.ClientAction.InvokeScript("TINY.box.hide();")
                    Exit Sub

                End If



                Dim adapter As New FundCenter2TableAdapters.BudgetDetailsTableAdapter
                Dim dtrow As New FundCenter2.BudgetDetailsDataTable
                Dim adapAt As New FundCenter2TableAdapters.AttachmentsTableAdapter
                Dim adapRev As New FundCenter2TableAdapters.BudgetRevPlansTableAdapter
                Dim dtRev As New FundCenter2.BudgetRevPlansDataTable
                Dim adapBud12 As New FundCenter2TableAdapters.Budget12TableAdapter
                Dim Badapter As New FundCenterRelationTableAdapters.BudgetDetailsTableAdapter
                If HdMyVersion.Value = "" Then
                    WebGrid1.ClientAction.Alert("กรุณาเลือก User Name")
                    WebGrid1.ClientAction.InvokeScript("TINY.box.hide();")
                    Exit Sub
                End If

                Dim newVersion As Integer = HdMyVersion.Value
                Dim countF1 As Integer = 0
                Dim topcount As Integer = 0
                Dim adapRel As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                Dim rfadap As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                topcount = Val(adapRel.CheckFundRelease(dd.Rows(0).Item("FundCenterCode"), Val(PlanYearsTxt.Text), newVersion))
                If topcount > 0 Then
                    WebGrid1.ClientAction.Alert("ระบบไม่สามารถ Copy Version ที่ทำการ Copy Version มาแล้วได้\nหากต้องการ Copy Version อีกครั้งให้ทำการ Release Version ก่อน จากนั้นทำการ Copy Version อีกครั้ง")
                    WebGrid1.ClientAction.InvokeScript("TINY.box.hide();")
                    Exit Sub
                End If
                For Each row As DataRow In dd.Rows
                    If Val(row.Item("level")) >= 4 Then
                        Dim chBudg As Integer = 0
                        chBudg = rfadap.CheckFundRelease(row.Item("FundCenterCode"), PlanYearsTxt.Text, "1")
                        If chBudg = 0 Then
                            adapRel.InsertRelease(PlanYearsTxt.Text, "N", "Y", "1", 0, Date.Now, HdUser.Value, row.Item("FundCenterCode"), PlanYearsTxt.Text)
                        End If
                    End If
                Next

                For Each row As DataRow In dd.Rows ' ,set FundCenterRelease

                    Dim chBudg As Integer = 0
                    chBudg = rfadap.CheckFundRelease(row.Item("FundCenterCode"), PlanYearsTxt.Text, newVersion)

                    If chBudg = 0 Then


                        dtrow = adapter.GetBudget_id(row.Item("FundCenterCode"), PlanYearsTxt.Text, row.Item("Now_version"))
                        'Response.Write(row.Item("FundCenterCode") & PlanYearsTxt.Text & row.Item("Now_version") & "<BR>")
                        For Each rowId As FundCenter2.BudgetDetailsRow In dtrow    'copy budget,copy attatment
                            Dim newId As Integer = adapter.copyVersion(newVersion, rowId.Id)
                            adapAt.copyAttachment(newId, rowId.Id)
                            adapBud12.copyBudget12(newVersion, newId, rowId.Id)

                        Next

                        dtRev = adapRev.GetDataBy_Func(row.Item("FundCenterCode"), PlanYearsTxt.Text, row.Item("Now_version"))
                        For Each rowIdR As FundCenter2.BudgetRevPlansRow In dtRev    'copy budget,copy attatment
                            adapRev.copyRevPlan(newVersion, rowIdR.Id)

                        Next

                        'Exit Sub

                        Dim adap As New checkPlanDSTableAdapters.FundCenterReleasesTableAdapter

                        Dim preVer As String = row.Item("Now_version")


                        adapRel.InsertRelease(PlanYearsTxt.Text, "N", "Y", newVersion, preVer, Date.Now, HdUser.Value, row.Item("FundCenterCode"), PlanYearsTxt.Text)

                        adapRel.UpdateOldRelease("N", Date.Now, Session("users"), row.Item("FundCenterCode"), PlanYearsTxt.Text, row.Item("Now_version"))

                    End If
                    countF1 += 1
                Next
                ' WebGrid1.ClientAction.Alert(HdMyVersion.Value)
                WebGrid1.ClientAction.Alert("Copy Version เรียบร้อยแล้ว")
                WebGrid1.ClientAction.InvokeScript("formrefresh()")
            ElseIf ActionType = "2" Then
                'WebGrid1.ClientAction.Alert("post2")

                'WebGrid1.ClientAction.Refresh()
                'Exit Sub


                Dim dd As New DataTable
                dd = WebGrid1.DataSource
                Dim count As Integer = 0
                Dim adapter As New FundCenter2TableAdapters.BudgetDetailsTableAdapter
                Dim dtrow As New FundCenter2.BudgetDetailsDataTable
                Dim adapAt As New FundCenter2TableAdapters.AttachmentsTableAdapter
                Dim adapBud12 As New FundCenter2TableAdapters.Budget12TableAdapter
                Dim Badapter As New FundCenterRelationTableAdapters.BudgetDetailsTableAdapter
                Dim rfadap As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                If HdMyVersion.Value = "" Then
                    WebGrid1.ClientAction.Alert("กรุณาเลือก User Name")
                    WebGrid1.ClientAction.InvokeScript("TINY.box.hide();")
                    Exit Sub
                End If
                Dim newVersion As Integer = HdMyVersion.Value
                'MsgBox(newVersion)
                'Exit Sub
                Dim countPln As Integer = 0
                Dim adapRel As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                Dim topcount As Integer = 0
                If dd.Rows.Count = 0 Then
                    WebGrid1.ClientAction.Alert("Not hove FundCenterCode")
                    WebGrid1.ClientAction.InvokeScript("TINY.box.hide();")
                    Exit Sub
                End If

                topcount = Val(adapRel.CheckFundRelease(dd.Rows(0).Item("FundCenterCode"), Val(PlanYearsTxt.Text), newVersion))

                If topcount > 0 Then
                    WebGrid1.ClientAction.Alert("ระบบไม่สามารถ Copy Version ที่ทำการ Copy Version มาแล้วได้\nหากต้องการ Copy Version อีกครั้งให้ทำการ Release Version ก่อน จากนั้นทำการ Copy Version อีกครั้ง")
                    WebGrid1.ClientAction.InvokeScript("TINY.box.hide();")
                    Exit Sub
                End If
                ' Dim dataCheck As FundCenter2.BudgetDetailsDataTable
                'For Each chrow As DataRow In dd.Rows
                '    dataCheck = adapter.CheckBudget(chrow.Item("FundCenterCode"), chrow.Item("Now_version"), Val(PlanYearsTxt.Text))
                '    If dataCheck.Count = 0 Then
                '        countPln = countPln + 1
                '    End If
                'Next
                'If countPln > 0 Then
                '    WebGrid1.ClientAction.Alert("มี " & countPln & " หน่วยงาน ที่ยังไม่ได้สร้างแผน")
                '    Exit Sub
                'End If
                Dim countF1 As Integer = 0
                For Each row As DataRow In dd.Rows

                    Dim chBudg As Integer = 0
                    chBudg = rfadap.CheckFundRelease(row.Item("FundCenterCode"), PlanYearsTxt.Text, newVersion)
                    'chBudg = Badapter.CountRecord(row.Item("FundCenterCode"), PlanYearsTxt.Text, newVersion)
                    'MsgBox(chBudg & " " & row.Item("FundCenterCode") & " " & PlanYearsTxt.Text & " " & newVersion)
                    If chBudg = 0 Then
                        ' MsgBox(row.Item("ReleaseFlag"))
                        Dim ReleaseF As String
                        Try
                            ReleaseF = row.Item("ReleaseFlag")
                        Catch ex As Exception
                            ReleaseF = "N"
                        End Try
                        Dim causeForce As String = HdCause.Value
                        If ReleaseF <> "Y" Then

                            Dim adap As New checkPlanDSTableAdapters.FundCenterReleasesTableAdapter
                            adap.UpdateForceFlag("Y", Date.Now, Session("users"), "Y", causeForce, row.Item("FundCenterCode"), PlanYearsTxt.Text, row.Item("Now_version"))
                        End If

                        'Dim adapRel As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                        Dim adap2 As New checkPlanDSTableAdapters.FundCenterReleasesTableAdapter

                        ' Dim exist2 As Integer
                        'If Val(row.Item("Now_version")) = 1 Then
                        '    exist2 = adap2.checkExist(row.Item("FundCenterCode"), Val(PlanYearsTxt.Text), row.Item("Now_version"))
                        '    If exist = 0 Then
                        '        adapRel.InsertRelease(PlanYearsTxt.Text, "Y", "N", 1, 0, Date.Now, HdUser.Value, row.Item("FundCenterCode"), Val(PlanYearsTxt.Text))
                        '    End If
                        'End If

                        dtrow = adapter.GetBudget_id(row.Item("FundCenterCode"), PlanYearsTxt.Text, row.Item("Now_version"))

                        For Each rowId As FundCenter2.BudgetDetailsRow In dtrow    'copy budget,copy attatment,set FundCenterRelease
                            Dim newId As Integer = adapter.copyVersion(newVersion, rowId.Id)
                            adapAt.copyAttachment(newId, rowId.Id)
                            adapBud12.copyBudget12(newVersion, newId, rowId.Id)
                        Next

                        Dim adapRev As New FundCenter2TableAdapters.BudgetRevPlansTableAdapter
                        Dim dtRev As New FundCenter2.BudgetRevPlansDataTable
                        dtRev = adapRev.GetDataBy_Func(row.Item("FundCenterCode"), PlanYearsTxt.Text, row.Item("Now_version"))
                        For Each rowIdR As FundCenter2.BudgetRevPlansRow In dtRev    'copy budget,copy attatment
                            adapRev.copyRevPlan(newVersion, rowIdR.Id)

                        Next



                        Dim preVer As String = row.Item("Now_version")

                        adapRel.InsertForce(PlanYearsTxt.Text, "N", "Y", newVersion, preVer, Date.Now, HdUser.Value, row.Item("FundCenterCode"), Val(PlanYearsTxt.Text), "N", causeForce)

                        Dim exist As Integer
                        exist = adap2.checkExist(row.Item("FundCenterCode"), Val(PlanYearsTxt.Text), row.Item("Now_version"))
                        If exist = 0 Then
                            adapRel.InsertForce(PlanYearsTxt.Text, "Y", "N", row.Item("Now_version"), "0", Date.Now, HdUser.Value, row.Item("FundCenterCode"), PlanYearsTxt.Text, "Y", causeForce)
                        Else
                            adapRel.UpdateOldRelease("N", Date.Now, Session("users"), row.Item("FundCenterCode"), PlanYearsTxt.Text, row.Item("Now_version"))
                        End If

                    End If


                    countF1 += 1
                Next

                WebGrid1.ClientAction.Alert("Force Copy Version เรียบร้อยแล้ว")
            Else


                Dim data As String = TryCast(Request("data"), String)

                'WebGrid1.ClientAction.Alert(data)
                Dim dd = data.Split(",")
                Dim fundCen As String = dd(0)
                Dim version As String = dd(1)
                Dim countr As Integer = 0
                Dim adapr As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                countr = adapr.checkCopy(fundCen, HdMyVersion.Value, Val(Session("PlanYear")))

                Dim adaprNow As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                Dim nversion As String = adaprNow.getNowVersion(fundCen, "Y", Val(Session("PlanYear")), "Y")

                ' WebGrid1.ClientAction.Alert(fundCen & "/" & version & "/" & nversion)
                If Val(nversion) < HdMyVersion.Value Then
                    Dim adapre As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                    adapre.ReleaseBackVersion("N", "Y", Session("users"), Date.Now, fundCen, Val(Session("PlanYear")), Val(nversion))

                    Dim parentfctr As String = ""
                    Dim adpparent As New FundCenterParentTableAdapters.FundCenterHierarchiesTableAdapter
                    Try
                        parentfctr = adpparent.GetParentFCTR(fundCen, Val(Session("PlanYear")))
                    Catch ex As Exception
                        parentfctr = ""
                    End Try

                    Dim Fadapter As New FundCenterRelationTableAdapters.FundCenterHierarchiesTableAdapter
                    Dim lvl As Integer = Val(Left(Fadapter.GetOrgLevel(fundCen, Val(Session("PlanYear")), 1), 1))
                    Dim parentcount As Integer = nversion - lvl
                    If parentcount < 0 Then
                        parentcount = 0
                    End If

                    Dim dd2 As New DataTable
                    dd2 = WebGrid1.DataSource
                    If parentcount > 0 Then

                        For n = 1 To parentcount

                            Dim exist As Integer = 0
                            For Each row2 As DataRow In dd2.Rows
                                If row2.Item("FundCenterCode").ToString.Trim = parentfctr Then
                                    exist += 1
                                End If
                                If exist > 0 Then
                                    Exit For
                                End If
                            Next
                            If exist > 0 And Val(nversion) > 1 Then

                                adapre.ReleaseBackVersion("N", "Y", Session("users"), Date.Now, parentfctr, Val(Session("PlanYear")), Val(nversion))
                                Try
                                    parentfctr = adpparent.GetParentFCTR(parentfctr, Val(Session("PlanYear")))
                                Catch ex As Exception
                                    parentfctr = ""
                                End Try

                            End If

                        Next

                    End If

                    WebGrid1.ClientAction.Alert("ยกเลิกส่งแผน หน่วยงานนี้เรียบร้อยแล้ว")
                    WebGrid1.ClientAction.InvokeScript("TINY.box.hide();")
                End If

                ' WebGrid1.ClientAction.Alert("ไม่สามารถ Release หน่วยงานนี้ได้")
                'End If



            End If
            Session.Remove("pageindex")
            Session.Add("pageindex", WebGrid1.GetCurrentPageIndex())
            Session.Remove("UserCombo")
            Session.Add("UserCombo", UsersWebCombo.Value)
            WebGrid1.ClientAction.InvokeScript("TINY.box.hide();")
            WebGrid1.ClientAction.InvokeScript("formrefresh()")
        End If
    End Sub

    Protected Sub WebGrid1_InitializeRow(sender As Object, e As RowEventArgs) Handles WebGrid1.InitializeRow
        Dim imag As New Image
        imag = CType(e.Row.Cells.GetNamedItem("FundCenter").GetTemplateContainer().FindControl("Image1"), Image)
        Try
            If e.Row.GetDataRow("ReleaseFlag") = "Y" Then

                imag.ImageUrl = "Images/planIc/sendIc.png"
                imag.ToolTip = "ส่งแผนแล้ว"
            ElseIf e.Row.GetDataRow("ReleaseFlag") = "N" Then
                imag.ImageUrl = "Images/planIc/nosend.png"
                imag.ToolTip = "ยังไม่ได้ส่งแผน"
            Else
                imag.ImageUrl = "Images/planIc/nobuild.png"
                imag.ToolTip = "ยังไม่ได้สร้างแผน"
            End If
        Catch ex As Exception
            imag.ImageUrl = "Images/planIc/nobuild.png"
        End Try


        Dim lb As New Label
        lb = CType(e.Row.Cells.GetNamedItem("FundCenter").GetTemplateContainer().FindControl("Label2"), Label)
        Dim shif As String = ""
        For i As Integer = 1 To Val(HdMyVersion.Value) - Val(e.Row.GetDataRow("level"))
            shif = shif & "--"
        Next
        lb.Text = shif
        ' MsgBox(HdMyVersion.Value & "/" & e.Row.GetDataRow("Now_version"))
        Try

            If HdMyVersion.Value = 1 Then
                'Dim imag2 As New Image
                'imag2 = CType(e.Row.Cells.GetNamedItem("Release").GetTemplateContainer().FindControl("Image2"), Image)
                Dim imag3 As New Image
                imag3 = CType(e.Row.Cells.GetNamedItem("Release").GetTemplateContainer().FindControl("Image3"), Image)

                'imag2.Visible = False
                imag3.Visible = False
            Else
                'Dim countr As Integer = 0
                'Dim adapr As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                'countr = adapr.checkCopy(e.Row.GetDataRow("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))

                'Dim imag2 As New Image
                'imag2 = CType(e.Row.Cells.GetNamedItem("Release").GetTemplateContainer().FindControl("Image2"), Image)
                Dim imag3 As New Image
                imag3 = CType(e.Row.Cells.GetNamedItem("Release").GetTemplateContainer().FindControl("Image3"), Image)

                'If countr > 0 Then

                '    imag2.Visible = True
                '    imag3.Visible = False
                'Else
                'check preversion
                '  Dim checknow As Integer
                Dim adaprNow As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
                Dim nversion As String = adaprNow.getNowVersion(e.Row.GetDataRow("FundCenterCode"), "Y", Val(Session("PlanYear")), "Y")

                If nversion = e.Row.GetDataRow("Now_version") Then
                    'imag2.Visible = False
                    imag3.Visible = True
                Else
                    'imag2.Visible = False
                    imag3.Visible = False
                End If

                'End If


            End If
        Catch ex As Exception
            logger.Error(ex.Message)
            logger.Error(ex.StackTrace)
        End Try


    End Sub
    Protected Sub UsersWebCombo_InitializeDataSource(sender As Object, e As ISNet.WebUI.WebCombo.DataSourceEventArgs) Handles UsersWebCombo.InitializeDataSource

        Dim adap As New MasterDataSetTableAdapters.Users2TableAdapter
        Dim dt As New MasterDataSet.Users2DataTable
        dt = adap.GetDataByPlanyear2(Session("PlanYear"))
        e.DataSource = dt

    End Sub

    Sub Alert(ByVal message As String)
        AlertText = "<script> alert('" & message & "');</script>"
    End Sub

    Protected Sub SearhBtn_Click(sender As Object, e As ImageClickEventArgs) Handles SearhBtn.Click

        'Alert(UsersWebCombo.Value)
        'PlanYearsTxt.Text = "3333"

        '  Session("usersNow") = UsersWebCombo.Value

        WebGrid1.ClearCachedDataSource()
        WebGrid1.ClientAction.Refresh()

    End Sub



    Protected Sub CopyAdvance_Click(sender As Object, e As ImageClickEventArgs) Handles CopyAdvance.Click
        If versionT.Text = "1" Or versionT.Text = "2" Or versionT.Text = "3" Or versionT.Text = "4" Or versionT.Text = "5" Then
            Alert("ไม่สามารถ Copy Version ไปยัง 1-5 ได้")
            WebGrid1.ClientAction.InvokeScript("TINY.box.hide();")
            Exit Sub
        End If
        If CheckBox4.Checked = True And CheckBox5.Checked = True Then
            Alert("ข้อ 4,5 ใช้ร่วมกันไม่ได้")
            WebGrid1.ClientAction.InvokeScript("TINY.box.hide();")
            Exit Sub

        End If
        Dim sql As String = ""
        Dim adap As New copyverAdvanceDSTableAdapters.BudgetDetailsTableAdapter
        Dim adapb As New copyverAdvanceDSTableAdapters.Budget12TableAdapter
        Dim dt As New copyverAdvanceDS.BudgetDetailsDataTable
        Dim dtb As New copyverAdvanceDS.Budget12DataTable
        If CheckBox4.Checked = True Then
            sql = " select sum(Element1) as Element1 ,sum(Element2) as Element2 ,sum(Element3) as Element3 ,sum(Element4) as Element4 ,sum(Element5) as Element5 ,sum(Element6) as Element6 ,sum(Element7) as Element7 ,sum(Element8) as Element8 ,sum(Element9) as Element9 ,"
            sql += " sum(Amount) as Amount,sum(NewQuantity) as NewQuantity,sum(ReplaceQuantity) as ReplaceQuantity, sum(Actual1) as Actual1, sum(Actual2) as Actual2, sum(Actual3) as Actual3, sum(Actual4) as Actual4,"
            sql += " sum(Actual5) as Actual5, sum(Actual6) as Actual6, sum(Actual7) as Actual7, sum(Actual8) as Actual8, sum(Actual9) as Actual9, sum(Actual10) as Actual10,"
            sql += " sum(Actual11) as Actual11, sum(Actual12) as Actual12 , sum(Actual13) as Actual13, sum(Actual14) as Actual14, sum(Actual15) as Actual15, "
            sql += " sum(Actual16)  as Actual16, FundCenter_FundCenterCode , Cmmt_CmmtCode ,  FunctionalArea,Product_ProductCode, ActivityType_ActivityTypeCode,AssetNo"
            sql += " FROM BudgetDetails where (PlanYear = " & planyearS.Text & ") AND (Version = '" & versionS.Text & "')"
            sql += " Group By FundCenter_FundCenterCode , Cmmt_CmmtCode , FunctionalArea,  Product_ProductCode, ActivityType_ActivityTypeCode, AssetNo "
            adap.GetDataByFilter(dt, sql)
            'Response.Write(sql)
            'Exit Sub
            If dt.Count > 0 Then
                Dim amount As Decimal
                Dim funcenter As String = ""
                adap.DeleteByPlanVersion(planyearT.Text, versionT.Text)
                For Each row As copyverAdvanceDS.BudgetDetailsRow In dt


                    If CheckBox1.Checked = True Then
                        Dim adapP As New copyverAdvanceDSTableAdapters.fundpathTableAdapter
                        Dim group As String = ""
                        group = adapP.getGroupP(planyearS.Text, row.FundCenter_FundCenterCode)


                        funcenter = getFund(group, planyearS.Text)
                        ' Response.Write("111/" & funcenter & "/#" & row.FundCenter_FundCenterCode & "/#" & group)
                    Else
                        funcenter = row.FundCenter_FundCenterCode
                    End If

                    If CheckBox3.Checked = True Then

                        amount = If(row.IsActual1Null, 0, row.Actual1) + If(row.IsActual2Null, 0, row.Actual2) + If(row.IsActual3Null, 0, row.Actual3) + If(row.IsActual4Null, 0, row.Actual4) + If(row.IsActual5Null, 0, row.Actual5) + If(row.IsActual6Null, 0, row.Actual6) + If(row.IsActual7Null, 0, row.Actual7) + If(row.IsActual8Null, 0, row.Actual8) + If(row.IsActual9Null, 0, row.Actual9) + If(row.IsActual10Null, 0, row.Actual10) + If(row.IsActual11Null, 0, row.Actual11) + If(row.IsActual12Null, 0, row.Actual12)

                    Else
                        amount = If(row.IsAmountNull, 0, row.Amount)
                    End If


                    'Dim adapAt As New FundCenter2TableAdapters.AttachmentsTableAdapter
                    'Dim adapBud12 As New FundCenter2TableAdapters.Budget12TableAdapter
                    ' Try

                    Dim newId As Integer = adap.InsertBudgetCopy(planyearT.Text, planyearT.Text, versionT.Text, If(row.IsAssetNoNull, Nothing, row.AssetNo), Nothing, Nothing, Nothing, If(row.IsElement1Null, Nothing, row.Element1), If(row.IsElement2Null, Nothing, row.Element2), If(row.IsElement3Null, Nothing, row.Element3), If(row.IsElement4Null, Nothing, row.Element4), If(row.IsElement5Null, Nothing, row.Element5), If(row.IsElement6Null, Nothing, row.Element6), If(row.IsElement7Null, Nothing, row.Element7), If(row.IsElement8Null, Nothing, row.Element8), If(row.IsElement9Null, Nothing, row.Element9), amount, If(row.IsNewQuantityNull, Nothing, row.NewQuantity), If(row.IsReplaceQuantityNull, Nothing, row.ReplaceQuantity), Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, If(row.IsFunctionalAreaNull, Nothing, row.FunctionalArea), If(row.IsActual1Null, Nothing, row.Actual1), If(row.IsActual2Null, Nothing, row.Actual2), If(row.IsActual3Null, Nothing, row.Actual3), If(row.IsActual4Null, Nothing, row.Actual4), If(row.IsActual5Null, Nothing, row.Actual5), If(row.IsActual6Null, Nothing, row.Actual6), If(row.IsActual7Null, Nothing, row.Actual7), If(row.IsActual8Null, Nothing, row.Actual8), If(row.IsActual9Null, Nothing, row.Actual9), If(row.IsActual10Null, Nothing, row.Actual10), If(row.IsActual11Null, Nothing, row.Actual11), If(row.IsActual12Null, Nothing, row.Actual12), If(row.IsActual13Null, Nothing, row.Actual13), If(row.IsActual14Null, Nothing, row.Actual14), If(row.IsActual15Null, Nothing, row.Actual15), If(row.IsActual16Null, Nothing, row.Actual16), Nothing, Nothing, Date.Now, Nothing, Session("users"), Nothing, planyearT.Text, Nothing, Nothing, Nothing, If(row.IsProduct_ProductCodeNull, Nothing, row.Product_ProductCode), planyearT.Text, funcenter, planyearT.Text, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, If(row.IsCmmt_CmmtCodeNull, Nothing, row.Cmmt_CmmtCode), planyearT.Text)

                    Dim sqlb As String = ""
                    sqlb = "  SELECT  sum(Amount1) as Amount1,sum(Amount2) as Amount2,sum(Amount3) as Amount3,sum(Amount4) as Amount4,sum(Amount5) as Amount5"
                    sqlb += " ,sum(Amount6) as Amount6,sum(Amount7) as Amount7,sum(Amount8) as Amount8,sum(Amount9) as Amount9,sum(Amount10) as Amount10"
                    sqlb += " ,sum(Amount11) as Amount11,sum(Amount12) as Amount12,sum(ForecastYear1) as ForecastYear1,"
                    sqlb += " sum(ForecastYear2) as ForecastYear2,sum(ForecastYear3) as ForecastYear3,sum(ForecastYear4) as ForecastYear4"
                    sqlb += " ,FundCenter_FundCenterCode,Cmmt_CmmtCode,FunctionalArea"
                    sqlb += " ,Product_ProductCode,ActivityType_ActivityTypeCode"
                    sqlb += "  FROM Budget12  where (PlanYear = " & planyearS.Text & ") AND (Version = '" & versionS.Text & "')"
                    sqlb += " and FundCenter_FundCenterCode = '" & funcenter & "'"
                    sqlb += " and " & If(row.IsCmmt_CmmtCodeNull, " Cmmt_CmmtCode IS NULL ", " Cmmt_CmmtCode  = '" & row.Cmmt_CmmtCode & "'")
                    sqlb += " and " & If(row.IsFunctionalAreaNull, " FunctionalArea is null ", " FunctionalArea = '" & row.FunctionalArea & "'")
                    sqlb += " and " & If(row.IsProduct_ProductCodeNull, " Product_ProductCode is null ", " Product_ProductCode = '" & row.Product_ProductCode & "'")
                    sqlb += " and " & If(row.IsActivityType_ActivityTypeCodeNull, " ActivityType_ActivityTypeCode is null ", " ActivityType_ActivityTypeCode = '" & row.ActivityType_ActivityTypeCode & "'")

                    sqlb += " Group By FundCenter_FundCenterCode , Cmmt_CmmtCode , FunctionalArea,  Product_ProductCode, ActivityType_ActivityTypeCode "


                    'Response.Write("<br>" & sqlb)
                    'Exit Sub
                    adapb.GetDatagroup(dtb, sqlb)
                    'adap.DeleteByPlanVersion(planyearD.Text, versionD.Text)
                    For Each rowb As copyverAdvanceDS.Budget12Row In dtb
                        Dim adb As New copyverAdvanceDSTableAdapters.Budget12TableAdapter
                        adb.InsertBudget12Copy(planyearT.Text, planyearT.Text, versionT.Text, If(rowb.IsFunctionalAreaNull, Nothing, rowb.FunctionalArea), Nothing, rowb.Amount1, rowb.Amount2, rowb.Amount3, rowb.Amount4, rowb.Amount5, rowb.Amount6, rowb.Amount7, rowb.Amount8, rowb.Amount9, rowb.Amount10, rowb.Amount11, rowb.Amount12, rowb.ForecastYear1, rowb.ForecastYear2, rowb.ForecastYear3, rowb.ForecastYear4, Nothing, Date.Now, Nothing, Session("users"), Nothing, rowb.FundCenter_FundCenterCode, planyearT.Text, Nothing, Nothing, If(rowb.IsCmmt_CmmtCodeNull, Nothing, rowb.Cmmt_CmmtCode), planyearT.Text, Nothing, Nothing, If(rowb.IsActivityType_ActivityTypeCodeNull, Nothing, rowb.ActivityType_ActivityTypeCode), Nothing, Nothing, If(rowb.IsProduct_ProductCodeNull, Nothing, rowb.Product_ProductCode), planyearT.Text, Nothing, Nothing, Nothing, newId)


                    Next


                    ' Catch ex As Exception
                    'MsgBox(Val(row.Element1))
                    'counterr += 1
                    ' End Try

                    'Dim newId As Integer = adap.InsertBudgetCopy(planyearT.Text, planyearT.Text, versionT.Text, row.AssetNo, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, row.FunctionalArea, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Date.Now, Nothing, Session("users"), Nothing, planyearT.Text, row.ActivityType_ActivityTypeCode, Nothing, Nothing, row.Product_ProductCode, planyearT.Text, funcenter, planyearT.Text, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, row.Cmmt_CmmtCode, planyearT.Text)

                Next

                logger.Info("User " & Session("users") & " copy new version")
                Alert("Copy Version เรียบร้อยแล้ว")
            End If


        ElseIf CheckBox2.Checked = True And CheckBox5.Checked = True Then

            sql = " select sum(Element1) as Element1 ,sum(Element2) as Element2 ,sum(Element3) as Element3 ,sum(Element4) as Element4 ,sum(Element5) as Element5 ,sum(Element6) as Element6 ,sum(Element7) as Element7 ,sum(Element8) as Element8 ,sum(Element9) as Element9 ,"
            sql += " sum(Amount) as Amount,sum(NewQuantity) as NewQuantity,sum(ReplaceQuantity) as ReplaceQuantity, sum(Actual1) as Actual1, sum(Actual2) as Actual2, sum(Actual3) as Actual3, sum(Actual4) as Actual4,"
            sql += " sum(Actual5) as Actual5, sum(Actual6) as Actual6, sum(Actual7) as Actual7, sum(Actual8) as Actual8, sum(Actual9) as Actual9, sum(Actual10) as Actual10,"
            sql += " sum(Actual11) as Actual11, sum(Actual12) as Actual12 , sum(Actual13) as Actual13, sum(Actual14) as Actual14, sum(Actual15) as Actual15, "
            sql += " sum(Actual16) as Actual16 ,  FundCenter_FundCenterCode , FunctionalArea,Cmmt_CmmtCode , AssetNo,"

            sql += "  ActivityType_ActivityTypeCode, Product_ProductCode,FP_CODE"
            sql += " from (select Element1,Element2,Element3,Element4,Element5,Element6,Element7,Element8,Element9,Amount,NewQuantity,ReplaceQuantity,  Actual1,  Actual2,  Actual3, Actual4,"
            sql += " Actual5,  Actual6,  Actual7,  Actual8, Actual9,  Actual10,"
            sql += " Actual11,  Actual12 , Actual13,  Actual14, Actual15, "
            sql += "  Actual16 , FundCenter_FundCenterCode , FunctionalArea ,  Cmmt_CmmtCode , AssetNo, "

            sql += "  ActivityType_ActivityTypeCode, Product_ProductCode,"
            sql += "   case when ISNUMERIC(SUBSTRING(isnull(FundedProgram,''), 1, 1)) = 1 then 'A' when SUBSTRING(isnull(FundedProgram,''), 1, 1)='' "
            sql += " then '' else SUBSTRING(isnull(FundedProgram,''), 1, 1) end AS FP_CODE FROM BudgetDetails "
            sql += " where (PlanYear = " & planyearS.Text & ") AND (Version = '" & versionS.Text & "')) as x"
            sql += " Group By FundCenter_FundCenterCode , Cmmt_CmmtCode , FunctionalArea,  Product_ProductCode, ActivityType_ActivityTypeCode, AssetNo , FP_CODE"

            ',isnull(Amount,0) as Amount
            adap.GetDataByFilter(dt, sql)
            ' Response.Write(sql)
            ' Exit Sub

            If dt.Count > 0 Then
                Dim amount As Decimal
                Dim funcenter As String
                adap.DeleteByPlanVersion(planyearT.Text, versionT.Text)
                For Each row As copyverAdvanceDS.BudgetDetailsRow In dt


                    If CheckBox1.Checked = True Then
                        Dim adapP As New copyverAdvanceDSTableAdapters.fundpathTableAdapter
                        Dim group As String = ""
                        group = adapP.getGroupP(planyearS.Text, row.FundCenter_FundCenterCode)


                        funcenter = getFund(group, planyearS.Text)
                        ' Response.Write("111/" & funcenter & "/#" & row.FundCenter_FundCenterCode & "/#" & group)
                    Else
                        funcenter = row.FundCenter_FundCenterCode
                    End If

                    If CheckBox3.Checked = True Then

                        amount = If(row.IsActual1Null, 0, row.Actual1) + If(row.IsActual2Null, 0, row.Actual2) + If(row.IsActual3Null, 0, row.Actual3) + If(row.IsActual4Null, 0, row.Actual4) + If(row.IsActual5Null, 0, row.Actual5) + If(row.IsActual6Null, 0, row.Actual6) + If(row.IsActual7Null, 0, row.Actual7) + If(row.IsActual8Null, 0, row.Actual8) + If(row.IsActual9Null, 0, row.Actual9) + If(row.IsActual10Null, 0, row.Actual10) + If(row.IsActual11Null, 0, row.Actual11) + If(row.IsActual12Null, 0, row.Actual12)

                    Else
                        amount = If(row.IsAmountNull, 0, row.Amount)
                    End If

                    Dim adapAt As New FundCenter2TableAdapters.AttachmentsTableAdapter
                    Dim adapBud12 As New FundCenter2TableAdapters.Budget12TableAdapter
                    Dim newId As Integer = adap.InsertBudgetCopy(planyearT.Text, planyearT.Text, versionT.Text, If(row.IsAssetNoNull, Nothing, row.AssetNo), Nothing, Nothing, Nothing, If(row.IsElement1Null, Nothing, row.Element1), If(row.IsElement2Null, Nothing, row.Element2), If(row.IsElement3Null, Nothing, row.Element3), If(row.IsElement4Null, Nothing, row.Element4), If(row.IsElement5Null, Nothing, row.Element5), If(row.IsElement6Null, Nothing, row.Element6), If(row.IsElement7Null, Nothing, row.Element7), If(row.IsElement8Null, Nothing, row.Element8), If(row.IsElement9Null, Nothing, row.Element9), amount, If(row.IsNewQuantityNull, Nothing, row.NewQuantity), If(row.IsReplaceQuantityNull, Nothing, row.ReplaceQuantity), Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, If(row.IsFunctionalAreaNull, Nothing, row.FunctionalArea), If(row.IsActual1Null, Nothing, row.Actual1), If(row.IsActual2Null, Nothing, row.Actual2), If(row.IsActual3Null, Nothing, row.Actual3), If(row.IsActual4Null, Nothing, row.Actual4), If(row.IsActual5Null, Nothing, row.Actual5), If(row.IsActual6Null, Nothing, row.Actual6), If(row.IsActual7Null, Nothing, row.Actual7), If(row.IsActual8Null, Nothing, row.Actual8), If(row.IsActual9Null, Nothing, row.Actual9), If(row.IsActual10Null, Nothing, row.Actual10), If(row.IsActual11Null, Nothing, row.Actual11), If(row.IsActual12Null, Nothing, row.Actual12), If(row.IsActual13Null, Nothing, row.Actual13), If(row.IsActual14Null, Nothing, row.Actual14), If(row.IsActual15Null, Nothing, row.Actual15), If(row.IsActual16Null, Nothing, row.Actual16), Nothing, Nothing, Date.Now, Nothing, Session("users"), Nothing, planyearT.Text, If(row.IsActivityType_ActivityTypeCodeNull, Nothing, row.ActivityType_ActivityTypeCode), Nothing, Nothing, If(row.IsProduct_ProductCodeNull, Nothing, row.Product_ProductCode), planyearT.Text, funcenter, planyearT.Text, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, If(row.IsCmmt_CmmtCodeNull, Nothing, row.Cmmt_CmmtCode), planyearT.Text)

                    Dim sqlb As String = ""

                    sqlb = " select   sum(Amount1) as Amount1,sum(Amount2) as Amount2,sum(Amount3) as Amount3,sum(Amount4) as Amount4,sum(Amount5) as Amount5"
                    sqlb += " ,sum(Amount6) as Amount6,sum(Amount7) as Amount7,sum(Amount8) as Amount8,sum(Amount9) as Amount9,sum(Amount10) as Amount10"
                    sqlb += " ,sum(Amount11) as Amount11,sum(Amount12) as Amount12,sum(ForecastYear1) as ForecastYear1,"
                    sqlb += " sum(ForecastYear2) as ForecastYear2,sum(ForecastYear3) as ForecastYear3,sum(ForecastYear4) as ForecastYear4"
                    sqlb += " ,FundCenter_FundCenterCode,Cmmt_CmmtCode,FunctionalArea"
                    sqlb += " ,Product_ProductCode,ActivityType_ActivityTypeCode, FP_CODE "
                    sqlb += "  from ( SELECT  Amount1, Amount2, Amount3, Amount4, Amount5"
                    sqlb += " , Amount6, Amount7, Amount8, Amount9, Amount10"
                    sqlb += " , Amount11, Amount12, ForecastYear1,"
                    sqlb += "  ForecastYear2, ForecastYear3, ForecastYear4"
                    sqlb += " ,FundCenter_FundCenterCode,Cmmt_CmmtCode,FunctionalArea"
                    sqlb += " ,Product_ProductCode,ActivityType_ActivityTypeCode,"
                    sqlb += "   case when ISNUMERIC(SUBSTRING(isnull(FundedProgram,''), 1, 1)) = 1 then 'A' when SUBSTRING(isnull(FundedProgram,''), 1, 1)='' "
                    sqlb += " then '' else SUBSTRING(isnull(FundedProgram,''), 1, 1) end AS FP_CODE "
                    sqlb += "  FROM Budget12  where (PlanYear = " & planyearS.Text & ") AND (Version = '" & versionS.Text & "')"
                    sqlb += " and FundCenter_FundCenterCode = '" & funcenter & "'"
                    sqlb += " and " & If(row.IsCmmt_CmmtCodeNull, " Cmmt_CmmtCode IS NULL ", " Cmmt_CmmtCode  = '" & row.Cmmt_CmmtCode & "'")
                    sqlb += " and " & If(row.IsFunctionalAreaNull, " FunctionalArea is null ", " FunctionalArea = '" & row.FunctionalArea & "'")
                    sqlb += " and " & If(row.IsProduct_ProductCodeNull, " Product_ProductCode is null ", " Product_ProductCode = '" & row.Product_ProductCode & "'")
                    sqlb += " and " & If(row.IsActivityType_ActivityTypeCodeNull, " ActivityType_ActivityTypeCode is null ", " ActivityType_ActivityTypeCode = '" & row.ActivityType_ActivityTypeCode & "'")
                    sqlb += " ) as x "
                    sqlb += " Group By FundCenter_FundCenterCode , Cmmt_CmmtCode , FunctionalArea,  Product_ProductCode, ActivityType_ActivityTypeCode , FP_CODE "


                    ' Response.Write("<br>" & sqlb)
                    'Exit Sub
                    adapb.GetDatagroup(dtb, sqlb)

                    For Each rowb As copyverAdvanceDS.Budget12Row In dtb
                        Dim adb As New copyverAdvanceDSTableAdapters.Budget12TableAdapter
                        adb.InsertBudget12Copy(planyearT.Text, planyearT.Text, versionT.Text, If(rowb.IsFunctionalAreaNull, Nothing, rowb.FunctionalArea), Nothing, rowb.Amount1, rowb.Amount2, rowb.Amount3, rowb.Amount4, rowb.Amount5, rowb.Amount6, rowb.Amount7, rowb.Amount8, rowb.Amount9, rowb.Amount10, rowb.Amount11, rowb.Amount12, rowb.ForecastYear1, rowb.ForecastYear2, rowb.ForecastYear3, rowb.ForecastYear4, Nothing, Date.Now, Nothing, Session("users"), Nothing, rowb.FundCenter_FundCenterCode, planyearT.Text, Nothing, Nothing, If(rowb.IsCmmt_CmmtCodeNull, Nothing, rowb.Cmmt_CmmtCode), planyearT.Text, Nothing, Nothing, If(rowb.IsActivityType_ActivityTypeCodeNull, Nothing, rowb.ActivityType_ActivityTypeCode), Nothing, Nothing, If(rowb.IsProduct_ProductCodeNull, Nothing, rowb.Product_ProductCode), planyearT.Text, Nothing, Nothing, Nothing, newId)


                    Next
                Next
                Alert("Copy Version เรียบร้อยแล้ว")
            End If


        ElseIf CheckBox5.Checked = True Then
            sql = " select sum(Element1) as Element1 ,sum(Element2) as Element2 ,sum(Element3) as Element3 ,sum(Element4) as Element4 ,sum(Element5) as Element5 ,sum(Element6) as Element6 ,sum(Element7) as Element7 ,sum(Element8) as Element8 ,sum(Element9) as Element9 ,"
            sql += " sum(Amount) as Amount,sum(NewQuantity) as NewQuantity,sum(ReplaceQuantity) as ReplaceQuantity, sum(Actual1) as Actual1, sum(Actual2) as Actual2, sum(Actual3) as Actual3, sum(Actual4) as Actual4,"
            sql += " sum(Actual5) as Actual5, sum(Actual6) as Actual6, sum(Actual7) as Actual7, sum(Actual8) as Actual8, sum(Actual9) as Actual9, sum(Actual10) as Actual10,"
            sql += " sum(Actual11) as Actual11, sum(Actual12) as Actual12 , sum(Actual13) as Actual13, sum(Actual14) as Actual14, sum(Actual15) as Actual15, "
            sql += " sum(Actual16) as Actual16 ,  FundCenter_FundCenterCode ,  Cmmt_CmmtCode "
            sql += " , FunctionalArea,  Product_ProductCode, ActivityType_ActivityTypeCode"

            sql += " ,  AssetNo, Project_ProjectCode, FundedProgram"
            sql += " FROM BudgetDetails where (PlanYear = " & planyearS.Text & ") AND (Version = '" & versionS.Text & "')"
            sql += " Group By FundCenter_FundCenterCode , Cmmt_CmmtCode , FunctionalArea,  Product_ProductCode, ActivityType_ActivityTypeCode, AssetNo, Project_ProjectCode, FundedProgram"


            adap.GetDataByFilter(dt, sql)
            'Response.Write(sql)
            'Exit Sub
            If dt.Count > 0 Then
                Dim amount As Decimal
                Dim funcenter As String
                adap.DeleteByPlanVersion(planyearT.Text, versionT.Text)
                For Each row As copyverAdvanceDS.BudgetDetailsRow In dt


                    If CheckBox1.Checked = True Then
                        Dim adapP As New copyverAdvanceDSTableAdapters.fundpathTableAdapter
                        Dim group As String = ""
                        group = adapP.getGroupP(planyearS.Text, row.FundCenter_FundCenterCode)


                        funcenter = getFund(group, planyearS.Text)
                        ' Response.Write("111/" & funcenter & "/#" & row.FundCenter_FundCenterCode & "/#" & group)
                    Else
                        funcenter = row.FundCenter_FundCenterCode
                    End If

                    If CheckBox3.Checked = True Then

                        amount = If(row.IsActual1Null, 0, row.Actual1) + If(row.IsActual2Null, 0, row.Actual2) + If(row.IsActual3Null, 0, row.Actual3) + If(row.IsActual4Null, 0, row.Actual4) + If(row.IsActual5Null, 0, row.Actual5) + If(row.IsActual6Null, 0, row.Actual6) + If(row.IsActual7Null, 0, row.Actual7) + If(row.IsActual8Null, 0, row.Actual8) + If(row.IsActual9Null, 0, row.Actual9) + If(row.IsActual10Null, 0, row.Actual10) + If(row.IsActual11Null, 0, row.Actual11) + If(row.IsActual12Null, 0, row.Actual12)

                    Else
                        amount = If(row.IsAmountNull, 0, row.Amount)
                    End If


                    Dim adapAt As New FundCenter2TableAdapters.AttachmentsTableAdapter
                    Dim adapBud12 As New FundCenter2TableAdapters.Budget12TableAdapter
                    Dim newId As Integer = adap.InsertBudgetCopy(planyearT.Text, planyearT.Text, versionT.Text, If(row.IsAssetNoNull, Nothing, row.AssetNo), Nothing, Nothing, Nothing, If(row.IsElement1Null, Nothing, row.Element1), If(row.IsElement2Null, Nothing, row.Element2), If(row.IsElement3Null, Nothing, row.Element3), If(row.IsElement4Null, Nothing, row.Element4), If(row.IsElement5Null, Nothing, row.Element5), If(row.IsElement6Null, Nothing, row.Element6), If(row.IsElement7Null, Nothing, row.Element7), If(row.IsElement8Null, Nothing, row.Element8), If(row.IsElement9Null, Nothing, row.Element9), amount, If(row.IsNewQuantityNull, Nothing, row.NewQuantity), If(row.IsReplaceQuantityNull, Nothing, row.ReplaceQuantity), Nothing, Nothing, Nothing, Nothing, Nothing, If(row.IsFundedProgramNull, Nothing, row.FundedProgram), Nothing, If(row.IsFunctionalAreaNull, Nothing, row.FunctionalArea), If(row.IsActual1Null, Nothing, row.Actual1), If(row.IsActual2Null, Nothing, row.Actual2), If(row.IsActual3Null, Nothing, row.Actual3), If(row.IsActual4Null, Nothing, row.Actual4), If(row.IsActual5Null, Nothing, row.Actual5), If(row.IsActual6Null, Nothing, row.Actual6), If(row.IsActual7Null, Nothing, row.Actual7), If(row.IsActual8Null, Nothing, row.Actual8), If(row.IsActual9Null, Nothing, row.Actual9), If(row.IsActual10Null, Nothing, row.Actual10), If(row.IsActual11Null, Nothing, row.Actual11), If(row.IsActual12Null, Nothing, row.Actual12), If(row.IsActual13Null, Nothing, row.Actual13), If(row.IsActual14Null, Nothing, row.Actual14), If(row.IsActual15Null, Nothing, row.Actual15), If(row.IsActual16Null, Nothing, row.Actual16), Nothing, Nothing, Date.Now, Nothing, Session("users"), Nothing, planyearT.Text, If(row.IsActivityType_ActivityTypeCodeNull, Nothing, row.ActivityType_ActivityTypeCode), Nothing, Nothing, If(row.IsProduct_ProductCodeNull, Nothing, row.Product_ProductCode), planyearT.Text, funcenter, planyearT.Text, If(row.IsProject_ProjectCodeNull, Nothing, row.Project_ProjectCode), planyearT.Text, Nothing, Nothing, Nothing, Nothing, If(row.IsCmmt_CmmtCodeNull, Nothing, row.Cmmt_CmmtCode), planyearT.Text)

                    Dim sqlb As String = ""
                    sqlb = "  SELECT  sum(Amount1) as Amount1,sum(Amount2) as Amount2,sum(Amount3) as Amount3,sum(Amount4) as Amount4,sum(Amount5) as Amount5"
                    sqlb += " ,sum(Amount6) as Amount6,sum(Amount7) as Amount7,sum(Amount8) as Amount8,sum(Amount9) as Amount9,sum(Amount10) as Amount10"
                    sqlb += " ,sum(Amount11) as Amount11,sum(Amount12) as Amount12,sum(ForecastYear1) as ForecastYear1,"
                    sqlb += " sum(ForecastYear2) as ForecastYear2,sum(ForecastYear3) as ForecastYear3,sum(ForecastYear4) as ForecastYear4"
                    sqlb += " ,FundCenter_FundCenterCode,Cmmt_CmmtCode,FunctionalArea"
                    sqlb += " ,Product_ProductCode,ActivityType_ActivityTypeCode, Project_ProjectCode, FundedProgram "
                    sqlb += "  FROM Budget12  where (PlanYear = " & planyearS.Text & ") AND (Version = '" & versionS.Text & "')"
                    sqlb += " and FundCenter_FundCenterCode = '" & funcenter & "'"
                    sqlb += " and " & If(row.IsCmmt_CmmtCodeNull, " Cmmt_CmmtCode IS NULL ", " Cmmt_CmmtCode  = '" & row.Cmmt_CmmtCode & "'")
                    sqlb += " and " & If(row.IsFunctionalAreaNull, " FunctionalArea is null ", " FunctionalArea = '" & row.FunctionalArea & "'")
                    sqlb += " and " & If(row.IsProduct_ProductCodeNull, " Product_ProductCode is null ", " Product_ProductCode = '" & row.Product_ProductCode & "'")
                    sqlb += " and " & If(row.IsActivityType_ActivityTypeCodeNull, " ActivityType_ActivityTypeCode is null ", " ActivityType_ActivityTypeCode = '" & row.ActivityType_ActivityTypeCode & "'")
                    sqlb += " and " & If(row.IsProject_ProjectCodeNull, " Project_ProjectCode is null ", " Project_ProjectCode = '" & row.Project_ProjectCode & "'")
                    sqlb += " and " & If(row.IsFundedProgramNull, " FundedProgram is null ", " FundedProgram = '" & row.FundedProgram & "'")
                    sqlb += " Group By FundCenter_FundCenterCode , Cmmt_CmmtCode , FunctionalArea,  Product_ProductCode, ActivityType_ActivityTypeCode, Project_ProjectCode, FundedProgram"


                    ' Response.Write("<br>" & sqlb)
                    'Exit Sub
                    adapb.GetDatagroup(dtb, sqlb)

                    For Each rowb As copyverAdvanceDS.Budget12Row In dtb
                        Dim adb As New copyverAdvanceDSTableAdapters.Budget12TableAdapter
                        adb.InsertBudget12Copy(planyearT.Text, planyearT.Text, versionT.Text, If(rowb.IsFunctionalAreaNull, Nothing, rowb.FunctionalArea), If(rowb.IsFundedProgramNull, Nothing, rowb.FundedProgram), rowb.Amount1, rowb.Amount2, rowb.Amount3, rowb.Amount4, rowb.Amount5, rowb.Amount6, rowb.Amount7, rowb.Amount8, rowb.Amount9, rowb.Amount10, rowb.Amount11, rowb.Amount12, rowb.ForecastYear1, rowb.ForecastYear2, rowb.ForecastYear3, rowb.ForecastYear4, Nothing, Date.Now, Nothing, Session("users"), Nothing, rowb.FundCenter_FundCenterCode, planyearT.Text, Nothing, Nothing, If(rowb.IsCmmt_CmmtCodeNull, Nothing, rowb.Cmmt_CmmtCode), planyearT.Text, Nothing, Nothing, If(rowb.IsActivityType_ActivityTypeCodeNull, Nothing, rowb.ActivityType_ActivityTypeCode), Nothing, Nothing, If(rowb.IsProduct_ProductCodeNull, Nothing, rowb.Product_ProductCode), planyearT.Text, If(rowb.IsProject_ProjectCodeNull, Nothing, rowb.Project_ProjectCode), Nothing, Nothing, newId)


                    Next


                Next
                Alert("Copy Version เรียบร้อยแล้ว")
            End If


        ElseIf CheckBox2.Checked = True Then


            sql = " select sum(Element1) as Element1 ,sum(Element2) as Element2 ,sum(Element3) as Element3 ,sum(Element4) as Element4 ,sum(Element5) as Element5 ,sum(Element6) as Element6 ,sum(Element7) as Element7 ,sum(Element8) as Element8 ,sum(Element9) as Element9 ,"
            sql += " sum(Amount) as Amount,sum(NewQuantity) as NewQuantity,sum(ReplaceQuantity) as ReplaceQuantity, sum(Actual1) as Actual1, sum(Actual2) as Actual2, sum(Actual3) as Actual3, sum(Actual4) as Actual4,"
            sql += " sum(Actual5) as Actual5, sum(Actual6) as Actual6, sum(Actual7) as Actual7, sum(Actual8) as Actual8, sum(Actual9) as Actual9, sum(Actual10) as Actual10,"
            sql += " sum(Actual11) as Actual11, sum(Actual12) as Actual12 , sum(Actual13) as Actual13, sum(Actual14) as Actual14, sum(Actual15) as Actual15, "
            sql += " sum(Actual16) as Actual16 , FundCenter_FundCenterCode , Cmmt_CmmtCode "
            sql += " , CmmtDetail_Id, Activity_ActivityCode,"
            sql += "  ActivityType_ActivityTypeCode,  Product_ProductCode,FP_CODE "
            sql += " from (select Element1,Element2,Element3,Element4,Element5,Element6,Element7,Element8,Element9,Amount,NewQuantity,ReplaceQuantity,  Actual1,  Actual2,  Actual3, Actual4,"
            sql += " Actual5,  Actual6,  Actual7,  Actual8, Actual9,  Actual10,"
            sql += " Actual11,  Actual12 , Actual13,  Actual14, Actual15, "
            sql += " Actual16 , FundCenter_FundCenterCode , Cmmt_CmmtCode "
            sql += " , CmmtDetail_Id, Activity_ActivityCode,"
            sql += "  ActivityType_ActivityTypeCode,  Product_ProductCode,"
            sql += " case when ISNUMERIC(SUBSTRING(isnull(FundedProgram,''), 1, 1)) = 1 then 'A' when SUBSTRING(isnull(FundedProgram,''), 1, 1)='' "
            sql += " then '' else SUBSTRING(isnull(FundedProgram,''), 1, 1) end AS FP_CODE FROM BudgetDetails "
            sql += " where (PlanYear = " & planyearS.Text & ") AND (Version = '" & versionS.Text & "')) as x"
            sql += " Group By FundCenter_FundCenterCode , Cmmt_CmmtCode ,CmmtDetail_Id,Activity_ActivityCode, ActivityType_ActivityTypeCode, Product_ProductCode,FP_CODE"

            adap.GetDataByFilter(dt, sql)
            ' Response.Write(sql)
            'Exit Sub
            If dt.Count > 0 Then
                Dim amount As Decimal
                Dim funcenter As String
                adap.DeleteByPlanVersion(planyearT.Text, versionT.Text)
                For Each row As copyverAdvanceDS.BudgetDetailsRow In dt

                    If CheckBox1.Checked = True Then
                        Dim adapP As New copyverAdvanceDSTableAdapters.fundpathTableAdapter
                        Dim group As String = ""
                        group = adapP.getGroupP(planyearS.Text, row.FundCenter_FundCenterCode)

                        funcenter = getFund(group, planyearS.Text)
                        ' Response.Write("111/" & funcenter & "/#" & row.FundCenter_FundCenterCode & "/#" & group)
                    Else
                        funcenter = row.FundCenter_FundCenterCode
                    End If

                    If CheckBox3.Checked = True Then

                        amount = If(row.IsActual1Null, 0, row.Actual1) + If(row.IsActual2Null, 0, row.Actual2) + If(row.IsActual3Null, 0, row.Actual3) + If(row.IsActual4Null, 0, row.Actual4) + If(row.IsActual5Null, 0, row.Actual5) + If(row.IsActual6Null, 0, row.Actual6) + If(row.IsActual7Null, 0, row.Actual7) + If(row.IsActual8Null, 0, row.Actual8) + If(row.IsActual9Null, 0, row.Actual9) + If(row.IsActual10Null, 0, row.Actual10) + If(row.IsActual11Null, 0, row.Actual11) + If(row.IsActual12Null, 0, row.Actual12)

                    Else
                        amount = If(row.IsAmountNull, 0, row.Amount)
                    End If

                    Dim adapAt As New FundCenter2TableAdapters.AttachmentsTableAdapter
                    Dim adapBud12 As New FundCenter2TableAdapters.Budget12TableAdapter
                    'Try
                    Dim newId As Integer = 0
                    If row.IsCmmtDetail_IdNull Then
                        newId = adap.InsertBudgetCopy(planyearT.Text, planyearT.Text, versionT.Text, Nothing, Nothing, Nothing, Nothing, If(row.IsElement1Null, Nothing, row.Element1), If(row.IsElement2Null, Nothing, row.Element2), If(row.IsElement3Null, Nothing, row.Element3), If(row.IsElement4Null, Nothing, row.Element4), If(row.IsElement5Null, Nothing, row.Element5), If(row.IsElement6Null, Nothing, row.Element6), If(row.IsElement7Null, Nothing, row.Element7), If(row.IsElement8Null, Nothing, row.Element8), If(row.IsElement9Null, Nothing, row.Element9), amount, If(row.IsNewQuantityNull, Nothing, row.NewQuantity), If(row.IsReplaceQuantityNull, Nothing, row.ReplaceQuantity), Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, If(row.IsActual1Null, Nothing, row.Actual1), If(row.IsActual2Null, Nothing, row.Actual2), If(row.IsActual3Null, Nothing, row.Actual3), If(row.IsActual4Null, Nothing, row.Actual4), If(row.IsActual5Null, Nothing, row.Actual5), If(row.IsActual6Null, Nothing, row.Actual6), If(row.IsActual7Null, Nothing, row.Actual7), If(row.IsActual8Null, Nothing, row.Actual8), If(row.IsActual9Null, Nothing, row.Actual9), If(row.IsActual10Null, Nothing, row.Actual10), If(row.IsActual11Null, Nothing, row.Actual11), If(row.IsActual12Null, Nothing, row.Actual12), If(row.IsActual13Null, Nothing, row.Actual13), If(row.IsActual14Null, Nothing, row.Actual14), If(row.IsActual15Null, Nothing, row.Actual15), If(row.IsActual16Null, Nothing, row.Actual16), Nothing, Nothing, Date.Now, Nothing, Session("users"), Nothing, planyearT.Text, If(row.IsActivityType_ActivityTypeCodeNull, Nothing, row.ActivityType_ActivityTypeCode), If(row.IsActivity_ActivityCodeNull, Nothing, row.Activity_ActivityCode), planyearT.Text, If(row.IsProduct_ProductCodeNull, Nothing, row.Product_ProductCode), planyearT.Text, funcenter, planyearT.Text, Nothing, planyearT.Text, Nothing, Nothing, Nothing, Nothing, If(row.IsCmmt_CmmtCodeNull, Nothing, row.Cmmt_CmmtCode), planyearT.Text)
                    Else
                        newId = adap.InsertBudgetCopy(planyearT.Text, planyearT.Text, versionT.Text, Nothing, Nothing, Nothing, Nothing, If(row.IsElement1Null, Nothing, row.Element1), If(row.IsElement2Null, Nothing, row.Element2), If(row.IsElement3Null, Nothing, row.Element3), If(row.IsElement4Null, Nothing, row.Element4), If(row.IsElement5Null, Nothing, row.Element5), If(row.IsElement6Null, Nothing, row.Element6), If(row.IsElement7Null, Nothing, row.Element7), If(row.IsElement8Null, Nothing, row.Element8), If(row.IsElement9Null, Nothing, row.Element9), amount, If(row.IsNewQuantityNull, Nothing, row.NewQuantity), If(row.IsReplaceQuantityNull, Nothing, row.ReplaceQuantity), Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, If(row.IsActual1Null, Nothing, row.Actual1), If(row.IsActual2Null, Nothing, row.Actual2), If(row.IsActual3Null, Nothing, row.Actual3), If(row.IsActual4Null, Nothing, row.Actual4), If(row.IsActual5Null, Nothing, row.Actual5), If(row.IsActual6Null, Nothing, row.Actual6), If(row.IsActual7Null, Nothing, row.Actual7), If(row.IsActual8Null, Nothing, row.Actual8), If(row.IsActual9Null, Nothing, row.Actual9), If(row.IsActual10Null, Nothing, row.Actual10), If(row.IsActual11Null, Nothing, row.Actual11), If(row.IsActual12Null, Nothing, row.Actual12), If(row.IsActual13Null, Nothing, row.Actual13), If(row.IsActual14Null, Nothing, row.Actual14), If(row.IsActual15Null, Nothing, row.Actual15), If(row.IsActual16Null, Nothing, row.Actual16), Nothing, Nothing, Date.Now, Nothing, Session("users"), Nothing, planyearT.Text, If(row.IsActivityType_ActivityTypeCodeNull, Nothing, row.ActivityType_ActivityTypeCode), If(row.IsActivity_ActivityCodeNull, Nothing, row.Activity_ActivityCode), planyearT.Text, If(row.IsProduct_ProductCodeNull, Nothing, row.Product_ProductCode), planyearT.Text, funcenter, planyearT.Text, Nothing, planyearT.Text, Nothing, row.CmmtDetail_Id, Nothing, Nothing, If(row.IsCmmt_CmmtCodeNull, Nothing, row.Cmmt_CmmtCode), planyearT.Text)
                    End If
                    If newId <> 0 Then
                        'If(row.IsCmmtDetail_IdNull, Nothing, row.CmmtDetail_Id)
                        'Catch ex As Exception
                        '    MsgBox(CmmtDetail_Id)
                        '    Exit Sub
                        'End Try
                        'err BudgetDetail_id

                        Dim sqlb As String = ""

                        sqlb = " select   sum(Amount1) as Amount1,sum(Amount2) as Amount2,sum(Amount3) as Amount3,sum(Amount4) as Amount4,sum(Amount5) as Amount5"
                        sqlb += " ,sum(Amount6) as Amount6,sum(Amount7) as Amount7,sum(Amount8) as Amount8,sum(Amount9) as Amount9,sum(Amount10) as Amount10"
                        sqlb += " ,sum(Amount11) as Amount11,sum(Amount12) as Amount12,sum(ForecastYear1) as ForecastYear1,"
                        sqlb += " sum(ForecastYear2) as ForecastYear2,sum(ForecastYear3) as ForecastYear3,sum(ForecastYear4) as ForecastYear4"
                        sqlb += " ,FundCenter_FundCenterCode,Cmmt_CmmtCode,CmmtDetail_Id"
                        sqlb += " ,Product_ProductCode,Activity_ActivityCode,ActivityType_ActivityTypeCode, FP_CODE "
                        sqlb += "  from ( SELECT  Amount1, Amount2, Amount3, Amount4, Amount5"
                        sqlb += " , Amount6, Amount7, Amount8, Amount9, Amount10"
                        sqlb += " , Amount11, Amount12, ForecastYear1,"
                        sqlb += "  ForecastYear2, ForecastYear3, ForecastYear4"
                        sqlb += " ,FundCenter_FundCenterCode,Cmmt_CmmtCode,CmmtDetail_Id"
                        sqlb += " ,Product_ProductCode,Activity_ActivityCode,ActivityType_ActivityTypeCode,"
                        sqlb += "   case when ISNUMERIC(SUBSTRING(isnull(FundedProgram,''), 1, 1)) = 1 then 'A' when SUBSTRING(isnull(FundedProgram,''), 1, 1)='' "
                        sqlb += " then '' else SUBSTRING(isnull(FundedProgram,''), 1, 1) end AS FP_CODE "
                        sqlb += "  FROM Budget12  where (PlanYear = " & planyearS.Text & ") AND (Version = '" & versionS.Text & "')"
                        sqlb += " and FundCenter_FundCenterCode = '" & funcenter & "'"
                        sqlb += " and " & If(row.IsCmmt_CmmtCodeNull, " Cmmt_CmmtCode IS NULL ", " Cmmt_CmmtCode  = '" & row.Cmmt_CmmtCode & "'")
                        sqlb += " and " & If(row.IsFunctionalAreaNull, " FunctionalArea is null ", " FunctionalArea = '" & row.FunctionalArea & "'")
                        sqlb += " and " & If(row.IsProduct_ProductCodeNull, " Product_ProductCode is null ", " Product_ProductCode = '" & row.Product_ProductCode & "'")
                        sqlb += " and " & If(row.IsActivityType_ActivityTypeCodeNull, " ActivityType_ActivityTypeCode is null ", " ActivityType_ActivityTypeCode = '" & row.ActivityType_ActivityTypeCode & "'")
                        sqlb += " and " & If(row.IsActivity_ActivityCodeNull, " Activity_ActivityCode is null ", " Activity_ActivityCode = '" & row.Activity_ActivityCode & "'")
                        sqlb += " and " & If(row.IsCmmtDetail_IdNull, " CmmtDetail_Id is null ", " CmmtDetail_Id = '" & row.CmmtDetail_Id & "'")
                        sqlb += " ) as x "
                        sqlb += " Group By FundCenter_FundCenterCode , Cmmt_CmmtCode ,CmmtDetail_Id,Activity_ActivityCode, ActivityType_ActivityTypeCode, Product_ProductCode,FP_CODE "


                        'Response.Write("<br>" & sqlb)
                        'Exit Sub
                        adapb.GetDatagroup(dtb, sqlb)

                        For Each rowb As copyverAdvanceDS.Budget12Row In dtb
                            Dim adb As New copyverAdvanceDSTableAdapters.Budget12TableAdapter
                            adb.InsertBudget12Copy(planyearT.Text, planyearT.Text, versionT.Text, If(rowb.IsFunctionalAreaNull, Nothing, rowb.FunctionalArea), Nothing, rowb.Amount1, rowb.Amount2, rowb.Amount3, rowb.Amount4, rowb.Amount5, rowb.Amount6, rowb.Amount7, rowb.Amount8, rowb.Amount9, rowb.Amount10, rowb.Amount11, rowb.Amount12, rowb.ForecastYear1, rowb.ForecastYear2, rowb.ForecastYear3, rowb.ForecastYear4, Nothing, Date.Now, Nothing, Session("users"), Nothing, rowb.FundCenter_FundCenterCode, planyearT.Text, Nothing, Nothing, If(rowb.IsCmmt_CmmtCodeNull, Nothing, rowb.Cmmt_CmmtCode), planyearT.Text, Nothing, planyearT.Text, If(rowb.IsActivityType_ActivityTypeCodeNull, Nothing, rowb.ActivityType_ActivityTypeCode), If(rowb.IsActivity_ActivityCodeNull, Nothing, rowb.Activity_ActivityCode), planyearT.Text, If(rowb.IsProduct_ProductCodeNull, Nothing, rowb.Product_ProductCode), planyearT.Text, Nothing, Nothing, Nothing, newId)
                        Next

                    End If
                Next
                Alert("Copy Version เรียบร้อยแล้ว")
            End If


        Else
            sql = " SELECT Id,PlanYear,BaseYear,Version,AssetNo,AssetDescription,AssetRowNo,OldAssetNo,Element1,Element2"
            sql += " ,Element3,Element4,Element5,Element6,Element7,Element8,Element9,Amount,NewQuantity,ReplaceQuantity"
            sql += " ,PricePerUnit,Note,Identification,FormId,FndPrgGenFlag,FundedProgram,TmpFundedProgram"
            sql += " ,FunctionalArea,Actual1, Actual2, Actual3,Actual4,Actual5, Actual6, Actual7,Actual8, Actual9, Actual10, Actual11"
            sql += " ,Actual12, Actual13, Actual14, Actual15, Actual16,Attachments_amount,ProductItemNo,CreatedDate,UpdatedDate"
            sql += " ,CreatedBy,UpdatedBy,ActivityType_PlanYear,ActivityType_ActivityTypeCode,Activity_ActivityCode,Activity_PlanYear"
            sql += " ,Product_ProductCode,Product_PlanYear,FundCenter_FundCenterCode,FundCenter_PlanYear,Project_ProjectCode"
            sql += " ,Project_PlanYear,Project_FundCenterCode,CmmtDetail_Id,Fund_FundCode,Fund_PlanYear,Cmmt_CmmtCode,Cmmt_PlanYear"
            sql += " FROM BudgetDetails where (PlanYear = " & planyearS.Text & ") AND (Version = '" & versionS.Text & "')"

            'Response.Write(sql)
            'Exit Sub
            adap.GetDataByFilter(dt, sql)

            If dt.Count > 0 Then
                Dim amount As Decimal
                Dim funcenter As String
                adap.DeleteByPlanVersion(planyearT.Text, versionT.Text)
                For Each row As copyverAdvanceDS.BudgetDetailsRow In dt


                    If CheckBox1.Checked = True Then
                        Dim adapP As New copyverAdvanceDSTableAdapters.fundpathTableAdapter
                        Dim group As String = ""
                        group = adapP.getGroupP(planyearS.Text, row.FundCenter_FundCenterCode)


                        funcenter = getFund(group, planyearS.Text)
                        ' Response.Write("111/" & funcenter & "/#" & row.FundCenter_FundCenterCode & "/#" & group)
                    Else
                        funcenter = row.FundCenter_FundCenterCode
                    End If


                    If CheckBox3.Checked = True Then

                        amount = If(row.IsActual1Null, 0, row.Actual1) + If(row.IsActual2Null, 0, row.Actual2) + If(row.IsActual3Null, 0, row.Actual3) + If(row.IsActual4Null, 0, row.Actual4) + If(row.IsActual5Null, 0, row.Actual5) + If(row.IsActual6Null, 0, row.Actual6) + If(row.IsActual7Null, 0, row.Actual7) + If(row.IsActual8Null, 0, row.Actual8) + If(row.IsActual9Null, 0, row.Actual9) + If(row.IsActual10Null, 0, row.Actual10) + If(row.IsActual11Null, 0, row.Actual11) + If(row.IsActual12Null, 0, row.Actual12)

                    Else
                        amount = If(row.IsAmountNull, 0, row.Amount)
                    End If

                    Dim adapAt As New FundCenter2TableAdapters.AttachmentsTableAdapter
                    Dim adapBud12 As New FundCenter2TableAdapters.Budget12TableAdapter
                    If row.IsCmmtDetail_IdNull Then
                        Dim newId As Integer = adap.InsertBudgetCopy(Val(planyearT.Text), Val(planyearT.Text), versionT.Text, If(row.IsAssetNoNull, Nothing, row.AssetNo), If(row.IsAssetDescriptionNull, Nothing, row.AssetDescription), If(row.IsAssetRowNoNull, Nothing, row.AssetRowNo), If(row.IsOldAssetNoNull, Nothing, row.OldAssetNo), If(row.IsElement1Null, Nothing, row.Element1), If(row.IsElement2Null, Nothing, row.Element2), If(row.IsElement3Null, Nothing, row.Element3), If(row.IsElement4Null, Nothing, row.Element4), If(row.IsElement5Null, Nothing, row.Element5), If(row.IsElement6Null, Nothing, row.Element6), If(row.IsElement7Null, Nothing, row.Element7), If(row.IsElement8Null, Nothing, row.Element8), If(row.IsElement9Null, Nothing, row.Element9), amount, If(row.IsNewQuantityNull, Nothing, row.NewQuantity), If(row.IsReplaceQuantityNull, Nothing, row.ReplaceQuantity), If(row.IsPricePerUnitNull, Nothing, row.PricePerUnit), If(row.IsNoteNull, Nothing, row.Note), If(row.IsIdentificationNull, Nothing, row.Identification), If(row.IsFormIdNull, Nothing, row.FormId), If(row.IsFndPrgGenFlagNull, Nothing, row.FndPrgGenFlag), If(row.IsFundedProgramNull, Nothing, row.FundedProgram), If(row.IsTmpFundedProgramNull, Nothing, row.TmpFundedProgram), If(row.IsFunctionalAreaNull, Nothing, row.FunctionalArea), If(row.IsActual1Null, Nothing, row.Actual1), If(row.IsActual2Null, Nothing, row.Actual2), If(row.IsActual3Null, Nothing, row.Actual3), If(row.IsActual4Null, Nothing, row.Actual4), If(row.IsActual5Null, Nothing, row.Actual5), If(row.IsActual6Null, Nothing, row.Actual6), If(row.IsActual7Null, Nothing, row.Actual7), If(row.IsActual8Null, Nothing, row.Actual8), If(row.IsActual9Null, Nothing, row.Actual9), If(row.IsActual10Null, Nothing, row.Actual10), If(row.IsActual11Null, Nothing, row.Actual11), If(row.IsActual12Null, Nothing, row.Actual12), If(row.IsActual13Null, Nothing, row.Actual13), If(row.IsActual14Null, Nothing, row.Actual14), If(row.IsActual15Null, Nothing, row.Actual15), If(row.IsActual16Null, Nothing, row.Actual16), If(row.IsAttachments_amountNull, Nothing, row.Attachments_amount), If(row.IsProductItemNoNull, Nothing, row.ProductItemNo), Date.Now, Nothing, Session("users"), Nothing, planyearT.Text, If(row.IsActivityType_ActivityTypeCodeNull, Nothing, row.ActivityType_ActivityTypeCode), If(row.IsActivity_ActivityCodeNull, Nothing, row.Activity_ActivityCode), planyearT.Text, If(row.IsProduct_ProductCodeNull, Nothing, row.Product_ProductCode), If(row.IsProduct_ProductCodeNull, Nothing, Val(planyearT.Text)), funcenter, planyearT.Text, If(row.IsProject_ProjectCodeNull, Nothing, row.Project_ProjectCode), planyearT.Text, If(row.IsProject_FundCenterCodeNull, Nothing, row.Project_FundCenterCode), Nothing, If(row.IsFund_FundCodeNull, Nothing, row.Fund_FundCode), planyearT.Text, If(row.IsCmmt_CmmtCodeNull, Nothing, row.Cmmt_CmmtCode), If(row.IsCmmt_CmmtCodeNull, Nothing, Val(planyearT.Text)))
                        adapAt.copyAttachment(newId, row.Id)
                        adapBud12.copyBudget12Advance(Val(planyearT.Text), versionT.Text, newId, row.Id)
                    Else
                        Dim newId As Integer = adap.InsertBudgetCopy(Val(planyearT.Text), Val(planyearT.Text), versionT.Text, If(row.IsAssetNoNull, Nothing, row.AssetNo), If(row.IsAssetDescriptionNull, Nothing, row.AssetDescription), If(row.IsAssetRowNoNull, Nothing, row.AssetRowNo), If(row.IsOldAssetNoNull, Nothing, row.OldAssetNo), If(row.IsElement1Null, Nothing, row.Element1), If(row.IsElement2Null, Nothing, row.Element2), If(row.IsElement3Null, Nothing, row.Element3), If(row.IsElement4Null, Nothing, row.Element4), If(row.IsElement5Null, Nothing, row.Element5), If(row.IsElement6Null, Nothing, row.Element6), If(row.IsElement7Null, Nothing, row.Element7), If(row.IsElement8Null, Nothing, row.Element8), If(row.IsElement9Null, Nothing, row.Element9), amount, If(row.IsNewQuantityNull, Nothing, row.NewQuantity), If(row.IsReplaceQuantityNull, Nothing, row.ReplaceQuantity), If(row.IsPricePerUnitNull, Nothing, row.PricePerUnit), If(row.IsNoteNull, Nothing, row.Note), If(row.IsIdentificationNull, Nothing, row.Identification), If(row.IsFormIdNull, Nothing, row.FormId), If(row.IsFndPrgGenFlagNull, Nothing, row.FndPrgGenFlag), If(row.IsFundedProgramNull, Nothing, row.FundedProgram), If(row.IsTmpFundedProgramNull, Nothing, row.TmpFundedProgram), If(row.IsFunctionalAreaNull, Nothing, row.FunctionalArea), If(row.IsActual1Null, Nothing, row.Actual1), If(row.IsActual2Null, Nothing, row.Actual2), If(row.IsActual3Null, Nothing, row.Actual3), If(row.IsActual4Null, Nothing, row.Actual4), If(row.IsActual5Null, Nothing, row.Actual5), If(row.IsActual6Null, Nothing, row.Actual6), If(row.IsActual7Null, Nothing, row.Actual7), If(row.IsActual8Null, Nothing, row.Actual8), If(row.IsActual9Null, Nothing, row.Actual9), If(row.IsActual10Null, Nothing, row.Actual10), If(row.IsActual11Null, Nothing, row.Actual11), If(row.IsActual12Null, Nothing, row.Actual12), If(row.IsActual13Null, Nothing, row.Actual13), If(row.IsActual14Null, Nothing, row.Actual14), If(row.IsActual15Null, Nothing, row.Actual15), If(row.IsActual16Null, Nothing, row.Actual16), If(row.IsAttachments_amountNull, Nothing, row.Attachments_amount), If(row.IsProductItemNoNull, Nothing, row.ProductItemNo), Date.Now, Nothing, Session("users"), Nothing, planyearT.Text, If(row.IsActivityType_ActivityTypeCodeNull, Nothing, row.ActivityType_ActivityTypeCode), If(row.IsActivity_ActivityCodeNull, Nothing, row.Activity_ActivityCode), planyearT.Text, If(row.IsProduct_ProductCodeNull, Nothing, row.Product_ProductCode), If(row.IsProduct_ProductCodeNull, Nothing, Val(planyearT.Text)), funcenter, planyearT.Text, If(row.IsProject_ProjectCodeNull, Nothing, row.Project_ProjectCode), planyearT.Text, If(row.IsProject_FundCenterCodeNull, Nothing, row.Project_FundCenterCode), row.CmmtDetail_Id, If(row.IsFund_FundCodeNull, Nothing, row.Fund_FundCode), planyearT.Text, If(row.IsCmmt_CmmtCodeNull, Nothing, row.Cmmt_CmmtCode), If(row.IsCmmt_CmmtCodeNull, Nothing, Val(planyearT.Text)))
                        adapAt.copyAttachment(newId, row.Id)
                        adapBud12.copyBudget12Advance(Val(planyearT.Text), versionT.Text, newId, row.Id)
                    End If

                    'Dim sql2 As String
                    'sql2 = " INSERT INTO [BudgetDetails] ([PlanYear], [BaseYear], [Version], [AssetNo], [AssetDescription], [AssetRowNo], [OldAssetNo], [Element1], [Element2], [Element3], [Element4], [Element5], [Element6], [Element7], [Element8], [Element9], [Amount], [NewQuantity], [ReplaceQuantity], [PricePerUnit], [Note], [Identification], [FormId], [FndPrgGenFlag], [FundedProgram], [TmpFundedProgram], [FunctionalArea], [Actual1], [Actual2], [Actual3], [Actual4], [Actual5], [Actual6], [Actual7], [Actual8], [Actual9], [Actual10], [Actual11], [Actual12], [Actual13], [Actual14], [Actual15], [Actual16], [Attachments_amount], [ProductItemNo], [CreatedDate], [UpdatedDate], [CreatedBy], [UpdatedBy], [ActivityType_PlanYear], [ActivityType_ActivityTypeCode], [Activity_ActivityCode], [Activity_PlanYear], [Product_ProductCode], [Product_PlanYear], [FundCenter_FundCenterCode], [FundCenter_PlanYear], [Project_ProjectCode], [Project_PlanYear], [Project_FundCenterCode], [CmmtDetail_Id], [Fund_FundCode], [Fund_PlanYear], [Cmmt_CmmtCode], [Cmmt_PlanYear])"
                    'sql2 += " VALUES (" & Val(planyearT.Text) & ",  Val(planyearT.Text), versionT.Text, If(row.IsAssetNoNull, Nothing, row.AssetNo), If(row.IsAssetDescriptionNull, Nothing, row.AssetDescription), If(row.IsAssetRowNoNull, Nothing, row.AssetRowNo), If(row.IsOldAssetNoNull, Nothing, row.OldAssetNo), If(row.IsElement1Null, Nothing, row.Element1), If(row.IsElement2Null, Nothing, row.Element2), If(row.IsElement3Null, Nothing, row.Element3), If(row.IsElement4Null, Nothing, row.Element4), If(row.IsElement5Null, Nothing, row.Element5), If(row.IsElement6Null, Nothing, row.Element6), If(row.IsElement7Null, Nothing, row.Element7), If(row.IsElement8Null, Nothing, row.Element8), If(row.IsElement9Null, Nothing, row.Element9), If(amount, Nothing, amount), If(row.IsNewQuantityNull, Nothing, row.NewQuantity), If(row.IsReplaceQuantityNull, Nothing, row.ReplaceQuantity), If(row.IsPricePerUnitNull, Nothing, row.PricePerUnit), If(row.IsNoteNull, Nothing, row.Note), If(row.IsIdentificationNull, Nothing, row.Identification), If(row.IsFormIdNull, Nothing, row.FormId), If(row.IsFndPrgGenFlagNull, Nothing, row.FndPrgGenFlag), If(row.IsFundedProgramNull, Nothing, row.FundedProgram), If(row.IsTmpFundedProgramNull, Nothing, row.TmpFundedProgram), If(row.IsFunctionalAreaNull, Nothing, row.FunctionalArea), If(row.IsActual1Null, Nothing, row.Actual1), If(row.IsActual2Null, Nothing, row.Actual2), If(row.IsActual3Null, Nothing, row.Actual3), If(row.IsActual4Null, Nothing, row.Actual4), If(row.IsActual5Null, Nothing, row.Actual5), If(row.IsActual6Null, Nothing, row.Actual6), If(row.IsActual7Null, Nothing, row.Actual7), If(row.IsActual8Null, Nothing, row.Actual8), If(row.IsActual9Null, Nothing, row.Actual9), If(row.IsActual10Null, Nothing, row.Actual10), If(row.IsActual11Null, Nothing, row.Actual11), If(row.IsActual12Null, Nothing, row.Actual12), If(row.IsActual13Null, Nothing, row.Actual13), If(row.IsActual14Null, Nothing, row.Actual14), If(row.IsActual15Null, Nothing, row.Actual15), If(row.IsActual16Null, Nothing, row.Actual16), If(row.IsAttachments_amountNull, Nothing, row.Attachments_amount), If(row.IsProductItemNoNull, Nothing, row.ProductItemNo), Date.Now, Nothing, Session("users"), Nothing, planyearT.Text, If(row.IsActivityType_ActivityTypeCodeNull, Nothing, row.ActivityType_ActivityTypeCode), If(row.IsActivity_ActivityCodeNull, Nothing, row.Activity_ActivityCode), planyearT.Text, If(row.IsProduct_ProductCodeNull, Nothing, row.Product_ProductCode), If(row.IsProduct_ProductCodeNull, Nothing, Val(planyearT.Text)), funcenter, planyearT.Text, If(row.IsProject_ProjectCodeNull, Nothing, row.Project_ProjectCode), planyearT.Text, If(row.IsProject_FundCenterCodeNull, Nothing, row.Project_FundCenterCode), If(row.IsCmmtDetail_IdNull, vbNullString, row.CmmtDetail_Id), If(row.IsFund_FundCodeNull, Nothing, row.Fund_FundCode), planyearT.Text, If(row.IsCmmt_CmmtCodeNull, Nothing, row.Cmmt_CmmtCode), If(row.IsCmmt_CmmtCodeNull, Nothing, Val(planyearT.Text)));"
                    'sql2 += " SELECT SCOPE_IDENTITY();"
                    'Response.Write(sql & "<br />")
                    'Dim bd_adapter As New MassChangeDSTableAdapters.BudgetDetailsTableAdapter
                    'Dim newId As Integer = bd_adapter.Execute(sql)


                    'insert
                Next
                Alert("Copy Version เรียบร้อยแล้ว")
            End If
        End If



        'Dim adap As New copyverAdvanceDSTableAdapters.BudgetDetailsTableAdapter
        'dtBget = adap.GetDataByPlanVer(planyearD.Text, versionD.Text)
        'Dim dtBget As New copyverAdvanceDS.BudgetDetailsDataTable



    End Sub

    Function getFund(ByVal groupP As String, ByVal planyear As Integer) As String

        Dim ogLevel As Integer
        Dim funcenter As String = ""
        Dim adap As New copyverAdvanceDSTableAdapters.fundpathTableAdapter
        For Each row As copyverAdvanceDS.fundpathRow In adap.GetOrgLevel(groupP, planyear)
            ogLevel = row.OrgLevel

            funcenter = row.FundCenter_FundCenterCode
        Next


        If ogLevel >= 30 Then
            Return funcenter
        End If
        Dim newGroup As String
        Dim len As Integer
        len = groupP.Length

        newGroup = groupP.Substring(0, len - 2)
        'Response.Write("*" & len & "/" & ogLevel & "/" & newGroup)
        'Exit Function
        Return getFund(newGroup, planyear)
    End Function

    Protected Sub DeleteBt_Click(sender As Object, e As ImageClickEventArgs) Handles DeleteBt.Click

        If versionD.Text = "1" Or versionD.Text = "2" Or versionD.Text = "3" Or versionD.Text = "4" Or versionD.Text = "5" Then
            Alert("ไม่สามารถลบ Version 1-5 ได้")
            Exit Sub
        End If
        Dim adap As New copyverAdvanceDSTableAdapters.BudgetDetailsTableAdapter
        Dim dtBget As New copyverAdvanceDS.BudgetDetailsDataTable
        dtBget = adap.GetDataByPlanVer(planyearD.Text, versionD.Text)
        Dim adapAtt As New copyverAdvanceDSTableAdapters.AttachmentsTableAdapter
        Dim adapBud12 As New copyverAdvanceDSTableAdapters.Budget12TableAdapter
        Dim adapfundAss As New copyverAdvanceDSTableAdapters.FundedProgramAssetsTableAdapter
        Dim adapfundPro As New copyverAdvanceDSTableAdapters.FundedProgramProjectsTableAdapter
        Dim adapBudRev As New copyverAdvanceDSTableAdapters.BudgetRevPlansTableAdapter
        Dim versionStr = Left(versionD.Text, 1)

        Dim a As Integer
        If (Not Integer.TryParse(versionStr, a)) Then
            adapfundPro.DeleteByVersionYear(planyearD.Text, versionD.Text)
            adapfundAss.DeleteByVersionYear(planyearD.Text, versionD.Text)
            adapBud12.DeleteQueryByVersionYear(planyearD.Text, versionD.Text)
            adapBudRev.DeleteVersionYear(planyearD.Text, versionD.Text)
        Else
            For Each row As copyverAdvanceDS.BudgetDetailsRow In dtBget
                adapBud12.Delete12ByBudDetailId(row.Id)
                adapfundAss.DeleteBD(row.Id)
                adapfundPro.DeleteBD(row.Id)
                adapAtt.DeleteAttByBudDeId(row.Id)
            Next
        End If

        Dim adapre As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
        adapre.SetCommandTimeOut(ConfigurationManager.AppSettings("QueryTimeOut"))
        adapre.DeleteReleaseVersion(versionD.Text, Val(planyearD.Text))
        adap.SetCommandTimeOut(ConfigurationManager.AppSettings("QueryTimeOut"))
        adap.DeleteByPlanVersion(planyearD.Text, versionD.Text)

        Alert("ลบข้อมูลเรียบร้อยแล้ว")
    End Sub

    Protected Sub ImageButton1_Click(sender As Object, e As ImageClickEventArgs) Handles ImageButton1.Click

        Dim countr As Integer = 0
        Dim adapr As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
        Dim dd As New DataTable
        dd = WebGrid1.DataSource

        Dim adapfundAss As New copyverAdvanceDSTableAdapters.FundedProgramAssetsTableAdapter
        Dim adapfundPro As New copyverAdvanceDSTableAdapters.FundedProgramProjectsTableAdapter

        For Each row As DataRow In dd.Rows
            countr = adapr.checkCopy(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))


            Dim adapre As New FundCenter2TableAdapters.FundCenterReleasesTableAdapter
            Dim preVersion As Integer = adapre.getPreVersion(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))

            'delete  budgetDetail,budget12,attachment,RevPlan,FundCenterRelease 

            Dim dtrow As New FundCenter2.BudgetDetailsDataTable
            Dim adapter As New FundCenter2TableAdapters.BudgetDetailsTableAdapter
            dtrow = adapter.GetBudget_id(row.Item("FundCenterCode"), Val(Session("PlanYear")), HdMyVersion.Value)
            'Response.Write(row.Item("FundCenterCode") & PlanYearsTxt.Text & row.Item("Now_version") & "<BR>")
            Dim adapAt As New FundCenter2TableAdapters.AttachmentsTableAdapter

            For Each rowId As FundCenter2.BudgetDetailsRow In dtrow    'copy budget,copy attatment
                adapAt.DeleteReleaseAtt(rowId.Id)

                adapfundAss.DeleteBD(rowId.Id)
                adapfundPro.DeleteBD(rowId.Id)
            Next
            adapter.DeleteReleaseBud(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))
            Dim adapRev As New FundCenter2TableAdapters.BudgetRevPlansTableAdapter
            adapRev.DeleteReleaseRev(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))
            Dim adapBud12 As New FundCenter2TableAdapters.Budget12TableAdapter
            adapBud12.DeleteRelease(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))

            adapre.DeleteReleaseFun(row.Item("FundCenterCode"), HdMyVersion.Value, Val(Session("PlanYear")))
            'Dim forceFlag As String = "N"
            'Try
            '    forceFlag = adapre.GetForceFlag(row.Item("FundCenterCode"), preVersion, Val(Session("PlanYear")))
            'Catch ex As Exception

            'End Try
            'If forceFlag = "Y" Then
            'adapre.ReleaseBackVersion3("Y", Session("users"), Date.Now, row.Item("FundCenterCode"), Val(Session("PlanYear")), preVersion)

            'Else
            adapre.ReleaseBackVersion2("Y", Session("users"), Date.Now, row.Item("FundCenterCode"), Val(Session("PlanYear")), preVersion)

            'End If

        Next
        AlertText = "<script> alert('Release แผนเรียบร้อยแล้ว');window.location = 'CopyVersionAdvance.aspx';</script>"
        Session.Remove("pageindex")
        Session.Add("pageindex", WebGrid1.GetCurrentPageIndex())
        Session.Remove("UserCombo")
        Session.Add("UserCombo", UsersWebCombo.Value)
        WebGrid1.ClientAction.InvokeScript("formrefresh()")
    End Sub
End Class
